# -*- coding: utf-8 -*-
from datetime import datetime
from datetime import timedelta
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import signals
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
from stdimage.fields import StdImageField

__author__ = 'Nataliel Vasconcelos'

class News(models.Model):
    publish = models.BooleanField('Publicar',default=True)
    detach = models.BooleanField('Destaque',default=False)
    title = models.CharField('Titulo',max_length=150)
    subTitle = models.CharField('SubTitulo',max_length=150)
    content = models.TextField('Conteúdo')
    imageDetach = StdImageField('Imagem Destaque',upload_to='media/imagem/noticia')
    date = models.DateTimeField('Data de publicação',default=datetime.now,blank=True)
    slugNews = models.SlugField(max_length=200, blank=True, unique=True)
    source = models.CharField('Fonte',max_length=150)

    class Meta:
        verbose_name_plural = 'Cadastro de notícias'
    def __unicode__(self):
        return self.title
    def get_absolute_url(self):
        return reverse('WebSite.views.newsIntern', kwargs={'slugNews': self.slugNews})

def news_pre_save(signal, instance, sender, **kwargs):
    """
    Estamos gerando uma nova slug para evitar duplicidade
    """
    if not instance.slugNews:
        slug = slugify(instance.title)
        newSlug = slug
        counter = 0

        while  News.objects.filter(slugNews = newSlug).exclude(id=instance.id).count() > 0:
            counter += 1
            newSlug = '%s-%d'%(slug, counter)
        instance.slugNews = newSlug
signals.pre_save.connect(news_pre_save, sender=News)


class Doubts(models.Model):
    publish=models.BooleanField('Publicar',default=True)
    title = models.CharField('Título',max_length=50)
    content = models.TextField('Descrição')
    date = models.DateTimeField('Data de publicação',default=datetime.now)

    class Meta:
        verbose_name_plural = 'FAQ - Dúvidas'
    def __unicode__(self):
        return self.title

choices = [ ("1","Resposta 1"), ("2", "Resposta 2" ), ("3", "Resposta 3" ),( "4", "Resposta 4" ), ( "5" , "Resposta 5") ]

class Quiz( models.Model):
    title = models.CharField( "Titulo" , max_length=100)
    created_date = models.DateField( default = datetime.now() )
    def __unicode__(self):
        return self.title

class Question(models.Model):
    text = models.CharField("Texto", max_length=200 )
    quiz = models.ForeignKey(Quiz)
    weight = models.IntegerField( "Peso" )
    answer1 = models.CharField( "Resposta 1", max_length=200)
    answer2 = models.CharField( "Resposta 2", max_length=200)
    answer3 = models.CharField( "Resposta 3", max_length=200, null = True, blank = True )
    answer4 = models.CharField( "Resposta 4", max_length=200, null = True, blank = True )
    answer5 = models.CharField( "Resposta 5", max_length=200, null = True, blank = True )
    correct_answer = models.CharField( "Resposta Correta", max_length = 1, choices = choices )
    def __unicode__(self):
        return self.text

class QuizHelper(models.Model):
    quiz = models.ForeignKey(Quiz)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    user = models.ForeignKey(User)
    duration = models.FloatField()
    correct_answers = models.IntegerField( default = 0 )
    points = models.IntegerField( default = 0 )
    def format_duration(self):
        timedelta_duration = timedelta( microseconds = self.duration )
        seconds = timedelta_duration.seconds
        hours = seconds // 3600
        seconds = seconds - hours * 3600
        minutes = seconds // 60
        seconds = seconds - ( minutes * 60 )
        return '%02d:%02d:%02d' % (hours, minutes, seconds)

class QuestionHelper(models.Model):
    question = models.ForeignKey(Question)
    quiz_helper = models.ForeignKey(QuizHelper)
    user_answer = models.CharField( max_length = 1, choices = choices )

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    valueQuiz = models.IntegerField(default=0)
    reponseQuiz = models.IntegerField(default=0)
    valueCorrect = models.IntegerField(default=0)
    pointsQuiz = models.IntegerField(default=0)
    totalTime = models.FloatField(default=0)